package org.alex.samples.service;

import java.util.ArrayList;
import java.util.List;

import org.alex.samples.dao.ISubjectDAO;
import org.alex.samples.model.Subject;
import org.alex.samples.vo.SubjectVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SubjectServiceImpl implements ISubjectService {
	
	@Autowired 
	ISubjectDAO SubjectDAO;
	
	@Override
	public List<Subject> FindAllSubject() {
		List<Subject> SubjectList = SubjectDAO.findAllSubject();
		return SubjectList;
	}
	@Override
	public void createSubject(Subject subject) {
		SubjectDAO.createSubject(subject);
	}
	@Override
	public void deleteSubject(int id) {
		SubjectDAO.deleteSubject(id);
	}
	@Override
	public SubjectVO FindSubjectById(int id) {
		SubjectVO subjectvo = new SubjectVO();
		Subject subject = SubjectDAO.FindSubjectById(id);
		subjectvo.setCount(subject.getCount());
		subjectvo.setDescription(subject.getDescription());
		subjectvo.setId(subject.getId());
		subjectvo.setName(subject.getName());
		subjectvo.setScore(subject.getScore());
		subjectvo.setStatus(subject.isStatus());
		subjectvo.setTime(subject.getTime());
		return subjectvo;
	}
	@Override
	public void editSubject(SubjectVO subjectvo) {
		Subject subject = SubjectDAO.FindSubjectById(subjectvo.getId());
		subject.setCount(subjectvo.getCount());
		subject.setDescription(subjectvo.getDescription());
		subject.setName(subjectvo.getName());
		subject.setScore(subjectvo.getScore());
		subject.setStatus(subjectvo.isStatus());
		subject.setTime(subjectvo.getTime());
		SubjectDAO.editSubject(subject);
	}
	@Override
	public List<Integer> findAllUserBySubject(Integer id) {
		List<Integer>list = SubjectDAO.findAllUserBySubject(id);
//		for(Integer i:list){

//			System.out.println(i);

//		}

		return list;
		
	}
	@Override
	public void saveSubjectStudent(List<Integer> list, Integer subjectId) {
		List<Integer> dbSubjectUserList = this.findAllUserBySubject(subjectId);
		//新勾选的学生

		List<Integer> insertList = new ArrayList<>();
		
		//取消勾选的学生

		List<Integer> delList = new ArrayList<>();
		
		for(Integer selectedUser:list){
			if(!dbSubjectUserList.contains(selectedUser)){
				insertList.add(selectedUser);
			}
		}
		for(Integer selectedUser:dbSubjectUserList){
			if(!list.contains(selectedUser)){
				delList.add(selectedUser);
			}
			
		}
		//分别更新数据库

		SubjectDAO.inserSubjectUsers(insertList,subjectId);
		
		SubjectDAO.deleteSubjectUsers(delList,subjectId);
	}
	
}
